import React, {useEffect, useState} from 'react';
import {Checkbox, Col, Form, Input, message, Modal, Row, Select} from 'antd';
import {connect} from 'umi';
import {debounce, removeFromArray} from '@/utils/common';
import './style.less';
import {CheckboxChangeEvent} from "antd/es/checkbox";
import {updateUserProject} from "@/services/information";

const EditProject = (props: any) => {
  const {visible, onCancel, data, row} = props;
  const [forms, setForms] = React.useState<any>([]);
  const [queryParams, setQueryParams] = React.useState<any>({});
  const projects =
    data.userJurisdictions.filter((value: any) => {
      const keys = Object.keys(queryParams);
      if (keys.length === 0) {
        return true;
      }
      for (let i in keys) {
        const key = keys[i];
        if (value[key].toString().indexOf(queryParams[key]) === -1) {
          return false;
        }
      }
      return true;
    })
  data.selected= [{
    identityId: 8,
    projectId: 2,
    roleIds: [29]
  }]

  function handleInputChange(e: any) {
    let {value} = e.target;
    setQueryParams({projectName: value})
  }

  function saveProjectItem(form: any, isAdd: boolean) {
    console.log('saveProjectItem',form)
    form.validateFields()
    let {name} = form['__INTERNAL__']
    if (isAdd) {
      let flag = true
      for (let i = 0; i < forms.length; i++) {
        let item = forms[i]
        if (item ['__INTERNAL__']['name'] === name) {
          flag = false
          break
        }
      }
      if (flag) {
        forms.push(form)
      }
    } else {
      removeFromArray(forms, '__INTERNAL__.name', name)
    }
    setForms(forms)
    console.log(forms)
  }

  function onOk(obj: any) {
    if (forms instanceof Array) {
      let checkAll: any = []
      forms.forEach(item => {
        checkAll.push(item.validateFields())
      })
      // if(checkAll.length)
      Promise.all(checkAll).then((v: any) => {
        // let  arr=v.map((item: any)=>(item.getFieldsValue()))
        let data1 = {projects: v, userId: row.id};
        updateUserProject(data1).then(resp => {
          if (resp.header&&resp.header.code === 200) {
            message.success('更新成功')
            onCancel()
          }
        })
      }).catch(err => {
      })
    }
  }

  let modalProps = {
    title: props.title,
    visible,
    onCancel,
    onOk,
    width: 660,
  };

  return (
    <Modal
      {...modalProps}
    >
      <div>
        <div className={'modal-top'}>

          <Col span={12}>
            {row.name}
          </Col>
          <Col span={12}>
            <Input allowClear
                   placeholder={'搜索项目名称'}
                   onChange={debounce(handleInputChange, 800)}
                   style={{width: 300}}
            />
          </Col>
        </div>
        <div className={'modal-body'}>
          {projects.map((item, key) =>
            <ProjectItem key={key} data={item} selected={data.selected.filter(select=>select.projectId===item.projectId)} callBack={saveProjectItem}/>)
          }
        </div>
      </div>
    </Modal>
  );

};

const ProjectItem: React.FC<any> = (props) => {
  const {
    callBack, data, selected
  } = props
  const {projectId, projectName, roles, identities} = data
  const [currentValue, setCurrentValue] = useState(selected[0])
  const [itemCheck, setItemCheck] = useState(currentValue!==undefined)
  const [ruleProps, setRuleProps] = useState({})
  const [form] = Form.useForm();
  let checkBoxProps = {
    checked: itemCheck,
  }
  const disabled = projectId === 33
  useEffect(()=>{
    if(currentValue){
      callBack(form, true)
    }
  })
  function handleChecked(v: CheckboxChangeEvent) {
    const {checked, value} = v.target
    setItemCheck(checked)
    if (checked) {
      setRuleProps({rules: [{required: true}]})
      callBack(form, true)
    } else {
      setRuleProps({rules: [{required: false}]})
      callBack(form, false)
    }
  }

  function onFinish(values) {
    console.log(values)
  }

  return <div className={'project-item'}>
    <Form form={form} name={projectId} onFinish={onFinish}>
      <Row>
        <Col span={12}>
          <Form.Item name='projectId' getValueProps={(v: any) => v} initialValue={projectId}>
            <Checkbox
              {...checkBoxProps}
              checked={itemCheck}
              disabled={disabled}
              onChange={v => {
                handleChecked(v)
              }}
              value={projectId}
            >
              {projectName}
            </Checkbox>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label={'用户等级'} name='identityId' {...ruleProps}  initialValue={currentValue?currentValue.identityId:null}>
            <Select
              placeholder={'请选择'}
              allowClear
              disabled={disabled}
              options={identities ? (identities.map((item: any, index: number) => ({
                  label: item.identityName,
                  value: item.identityId
                })
              )) : null}
            />
          </Form.Item>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <Form.Item label={'角色'} name='roleIds'  {...ruleProps}  initialValue={currentValue?currentValue.roleIds:[]} >
            <Select style={{width: '100%'}}
                    mode={'multiple'}
                    placeholder={'请选择'}
                    allowClear
                    disabled={disabled}
                    options={roles ? (roles.map((item: any, index: number) => ({label: item.name, value: item.id})
                    )) : null}
            >
            </Select>
          </Form.Item>
        </Col>
      </Row>
    </Form>
  </div>
}

export default connect(() => (
  {}
))(EditProject);
